﻿using SqlSugar;
using WebApplication1.Models.RBAC;
using WebApplication1.Models.商品信息;
using WebApplication1.Models.商品信息.企业;
using WebApplication1.Models.商品信息.养殖;
using WebApplication1.Models.商品信息.地址;
using WebApplication1.Models.商品信息.屠宰;
using WebApplication1.Models.商品信息.深加工;

namespace WebApplication1
{
    public static class SqlsugarException
    {
        public static IServiceCollection AddSqlsugar(this IServiceCollection services, string config)
        {
           services.AddScoped<ISqlSugarClient>(s =>
            {
                //Scoped用SqlSugarClient 
                SqlSugarClient sqlSugar = new SqlSugarClient(new ConnectionConfig()
                {
                    DbType = SqlSugar.DbType.MySql,
                    ConnectionString = config,//builder.Configuration["ConnectionStrings:constr"],//从配置文件中获取
                    IsAutoCloseConnection = true,
                },
                db =>
                {
                    //每次上下文都会执行

                    //获取IOC对象不要求在一个上下文
                    //var log=s.GetService<Log>()

                    //获取IOC对象要求在一个上下文
                    //var appServive = s.GetService<IHttpContextAccessor>();
                    //var log= appServive?.HttpContext?.RequestServices.GetService<Log>();
                    //建库：如果不存在创建数据库存在不会重复创建 createdb
                    db.DbMaintenance.CreateDatabase(); // 注意 ：Oracle和个别国产库需不支持该方法，需要手动建库 
                                                        //创建表：根据实体类CodeFirstTable1  (所有数据库都支持)    
                    db.CodeFirst.InitTables<GoodsModel, GoodNameModel, UserModel, BreedingModel, ImmunityModel>();
                    db.CodeFirst.InitTables<CommpanyModel, EnterpriseModel, QuarantineModel, CommpanyAddressModel, EnterprisePicModel>();
                    db.CodeFirst.InitTables<QualificationModel, SlaughterModel, CommpanyPicModel, CityModel, ProvincialModel>();
                    db.CodeFirst.InitTables<AdditiveModel, AdditivepicModel, DeepModel, FeedstockModel, FeedstockpicModel>();
                    db.CodeFirst.InitTables<FoodSafetyModel, MaterialModel, MaterialpicModel, PackagingModel, PackagingpicModel>();
                    db.CodeFirst.InitTables<ProcessingCommpany, ProcessingpicModel>();

                    db.Aop.OnLogExecuting = (sql, pars) =>
                    {
                        //Console.WriteLine(sql);//输出sql,查看执行sql 性能无影响
                    };
                });

                return sqlSugar;
            });
            return services;
        }
    }
}
